<?php

Yii::import('application.vendors.*');
require_once('ChartDirector/lib/phpchartdir.php');
require_once('ChartDirector/lib/financefunction.php');

class PortfolioController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'PortfolioReturn', 'Testing', 'PortfolioIndex','delete'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'orderlog','createDividend','createOption','createSplit','component'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
	public function actionComponent() {       
		if(isset($_POST['component_port']))
		{
			$tickerCount = Portfolio::model()->findAll(array('select' => 'companyID', 'distinct' => true, 'condition' => "portfolionameID = " . $_POST['component_port']));
			$count = count($tickerCount);
			foreach($tickerCount as $temp_data)
			{
				$com = Componentportfolio::model()->findByAttributes(array('companyID' => $temp_data['companyID']));
				if($com!=null)
				{
					
					//$model_com = Componentportfolio::model()->findByAttributes(array('id'=>$abc));
					$pieces = explode("/", $_POST['date_'.$temp_data['companyID']]); /// xu ly thong tin ngay bat dau
				    $date_save = $pieces[2] . "-" . $pieces[1] . "-" . $pieces[0] . " 00:00:00";
						
					$com->date = $date_save;
						
					$com->quantity = $_POST['quantity_'.$temp_data['companyID']];
					$com->save();
				} else {
					$model_com = new Componentportfolio;
					$pieces = explode("/", $_POST['date_'.$temp_data['companyID']]); /// xu ly thong tin ngay bat dau
				    $date_save = $pieces[2] . "-" . $pieces[1] . "-" . $pieces[0] . " 00:00:00";
						
					$model_com->date = $date_save;
					$model_com->quantity = $_POST['quantity_'.$temp_data['companyID']];
					$model_com->companyID = $temp_data['companyID'];
					$model_com->portfolionameID = $_POST['component_port'];
					$model_com->save();
				}
			}
			$this->redirect(array('orderlog', 'port' => $_GET['port']));
		}
        $this->render('component', array(
            'port' => $_GET['port'],
        ));
    }
	
    public function actionCreate() {
        $model = new Portfolio;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Portfolio'])) {
            $model->attributes = $_POST['Portfolio'];
			if (preg_match('/[0-3]\d\/[01]\d\/\d{4}/', $model->date)) {
				$model->date = Stock::uk_date_to_mysql_date($model->date);
			}
            if ($model->save())
                $this->redirect(array('orderlog', 'port' => $_GET['port']));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }
	
	public function actionCreateDividend() {
        $model = new Portfolio;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Portfolio'])) {
            $model->attributes = $_POST['Portfolio'];
			if (preg_match('/[0-3]\d\/[01]\d\/\d{4}/', $model->date)) {
				$model->date = Stock::uk_date_to_mysql_date($model->date);
			}
            if ($model->save())
                $this->redirect(array('orderlog', 'port' => $_GET['port']));
        }

        $this->render('createDividend', array(
            'model' => $model,
        ));
    }
	
	public function actionCreateSplit() {
        $model = new Portfolio;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Portfolio'])) {
            $model->attributes = $_POST['Portfolio'];
			if (preg_match('/[0-3]\d\/[01]\d\/\d{4}/', $model->date)) {
				$model->date = Stock::uk_date_to_mysql_date($model->date);
			}
            if ($model->save())
                $this->redirect(array('orderlog', 'port' => $_GET['port']));
        }

        $this->render('createSplit', array(
            'model' => $model,
        ));
    }
	
	public function actionCreateOption() {
        $model = new Portfolio;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Portfolio'])) {
            $model->attributes = $_POST['Portfolio'];
			if (preg_match('/[0-3]\d\/[01]\d\/\d{4}/', $model->date)) {
				$model->date = Stock::uk_date_to_mysql_date($model->date);
			}
            if ($model->save())
                $this->redirect(array('orderlog', 'port' => $_GET['port']));
        }

        $this->render('createOption', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Portfolio'])) {
            $model->attributes = $_POST['Portfolio'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Portfolio');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Portfolio('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Portfolio']))
            $model->attributes = $_GET['Portfolio'];
        
        $this->render('admin', array(
            'model' => $model,
        ));
    }
    
    /**
     * Manages orderlog
     */
    public function actionOrderLog() {
        if (isset($_GET['port'])) {
            //For Buy Log
            $buylog = new Portfolio('search');
            $buylog->unsetAttributes();  // clear any default values
            $buylog->portfolionameID = $_GET['port'];
            $buylog->type = 0;
            $buylog->status = 0;
            if (isset($_GET['Portfolio']))
                $buylog->attributes = $_GET['Portfolio'];

            //Sell Log
            $selllog = new Portfolio('search');
            $selllog->unsetAttributes();  // clear any default values
            $selllog->portfolionameID = $_GET['port'];
            $selllog->type = 1;
            $selllog->status = 0;
            if (isset($_GET['Portfolio']))
                $selllog->attributes = $_GET['Portfolio'];

            //Dividend in Share
            $divinshare = new Portfolio('search');
            $divinshare->unsetAttributes();  // clear any default values
            $divinshare->portfolionameID = $_GET['port'];
            $divinshare->type = 0;
            $divinshare->status = 1;
            if (isset($_GET['Portfolio']))
                $divinshare->attributes = $_GET['Portfolio'];

            //Dividend in Cash
            $divincash = new Dividend('search');
            $divincash->portfolionameID = $_GET['port'];
            if (isset($_GET['Dividend']))
                $divincash->attributes = $_GET['Dividend'];

            //Split
            $split = new Portfolio('search');
            $split->unsetAttributes();  // clear any default values
            $split->portfolionameID = $_GET['port'];
            $split->type = 0;
            $split->status = 2;
            if (isset($_GET['Portfolio']))
                $split->attributes = $_GET['Portfolio'];

            //Option
            $option = new Portfolio('search');
            $option->unsetAttributes();  // clear any default values
            $option->portfolionameID = $_GET['port'];
            $option->status = 3;
            if (isset($_GET['Portfolio']))
                $option->attributes = $_GET['Portfolio'];

            $this->render('orderlog', array(
                'buylog' => $buylog,
                'selllog' => $selllog,
                'divinshare' => $divinshare,
                'divincash' => $divincash,
                'split' => $split,
                'option' => $option,
            ));
        } else {
            $this->render('orderlog', array());
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Portfolio::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'portfolio-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    //// BEGIN --- Function lay gia dong cua cua co phieu
    protected function getClosePrice($ticket, $date) {
        $price = 0;
        while ($price == 0) {
            $stock = Stock::model()->findByAttributes(array('companyID' => $ticket, 'timestamp' => $date));
            if ($stock != null)
                $price = $stock->close;

            $date_next = new DateTime($date);
            $date_next->modify('-1 day');
            $now_next = $date_next->format("Y-m-d 00:00:00");
            $date = $now_next;
        }
        return $price;
    }

    /////// END --- Function lay gia dong cua cua co phieu

    ///// BEGIN --- xoay ma tran- dung trong ham tinh gia dieu chinh
    protected function matrixRotation($A) {
        $temp = array();
        $j = 0;
        for ($i = count($A) - 1; $i >= 0; $i--) {
            $temp[$j] = $A[$i];
            $j++;
        }
        return $temp;
    }

    /// END --- xoay ma tran- dung trong ham tinh gia dieu chinh
    ///// BEGIN ---- Fucntion tinh Beta cua co phieu
    protected function getBetaStock($ticket, $dateBegin, $dateEnd, $house, $step) {
        $closeData = array();
        $house = $house;
        $fromMa = $dateBegin;
        $toMa = $dateEnd;
        $maChungKhoan = $ticket;
        $ReturnStep = $step;
        $testMode = 0;
        //$StockObj = Company::model()->findByAttributes(array('ticket' => $maChungKhoan));
        $query = "companyID = " . $maChungKhoan . " and (timestamp BETWEEN '" . $fromMa . "' and '" . $toMa . "') ORDER BY timestamp ASC";
        $db = Stock::model()->findAll($query);
        if ($house == 1)
            $StockObj = Company::model()->findByAttributes(array('ticket' => 'VNINDEX')); else if ($house == 2)
            $StockObj = Company::model()->findByAttributes(array('ticket' => 'HASTC'));
        $query = "companyID = " . $StockObj->id . " and (timestamp BETWEEN '" . $fromMa . "' and '" . $toMa . "')  ORDER BY timestamp DESC";
        $VNINDEX = Stock::model()->findAll($query);

        $count = count($db) - 1;
        $aaf = adjustPrice($db);
        for ($i = 0; $i <= $count; ++$i) {
            if ($db[$i]->close != '0' && $i % $ReturnStep == 0) {
                $closeData[] = round($db[$i]->close * $aaf[$i], 3);
                $VNINDEX_Data[] = round($VNINDEX[$i]->close, 3);
            }
        }
        $temp = array();
        for ($i = 0; $i <= $count; ++$i) {
            if ($db[$i]->close != '0' && $i % $ReturnStep == 0)
                array_push($temp, $db[$i]->close);
        }

        $dateStamp = array();
        for ($i = 0; $i <= $count; ++$i) {
            if ($db[$i]->timestamp != '0' && $i % $ReturnStep == 0)
                array_push($dateStamp, $db[$i]->timestamp);
        }
        $closeData = $this->matrixRotation($closeData);
        $temp = $this->matrixRotation($temp);
        $dateStamp = $this->matrixRotation($dateStamp);
        $ReturnValueStock = array();
        $ReturnValueVNIndex = array();
        for ($i = 0; $i < count($closeData) - 1; $i++) {

            if ($closeData[$i + 1] != 0)
                $Log10Temp = log(floatval($closeData[$i]) / floatval($closeData[$i + 1]));
            else
                $Log10Temp = log(floatval($closeData[$i] - 1) / floatval($closeData[$i]));
            $Log10TempVN = log(floatval($VNINDEX_Data[$i]) / floatval($VNINDEX_Data[$i + 1]));
            array_push($ReturnValueStock, $Log10Temp);
            array_push($ReturnValueVNIndex, $Log10TempVN);
        }
        //echo array_sum($ReturnValueStock).count($ReturnValueStock);
        $returnValue = array_sum($ReturnValueStock) / count($ReturnValueStock);
        $SSTot = 0;
        $SSReg = 0;
        for ($i = 0; $i < count($ReturnValueStock); $i++) {
            $SSTot = $SSTot + ($ReturnValueStock[$i] - $returnValue) * ($ReturnValueStock[$i] - $returnValue);
        }
        $averStock = array_sum($ReturnValueStock) / count($ReturnValueStock);
        $averVN = array_sum($ReturnValueVNIndex) / count($ReturnValueVNIndex);

        $ReturnAverageValueStock = array();
        $ReturnAverageValueVNIndex = array();
        for ($i = 0; $i < count($ReturnValueStock); $i++) {
            array_push($ReturnAverageValueStock, $ReturnValueStock[$i] - $averStock);
            array_push($ReturnAverageValueVNIndex, $ReturnValueVNIndex[$i] - $averVN);
        }
        $covarTemp = array();
        for ($i = 0; $i < count($ReturnValueStock); $i++) {
            array_push($covarTemp, $ReturnAverageValueStock[$i] * $ReturnAverageValueVNIndex[$i]);
        }
        $Correlation = array_sum($covarTemp) / count($covarTemp);
        $std_index = Stock::model()->standard_deviation($ReturnValueVNIndex, true) * Stock::model()->standard_deviation($ReturnValueVNIndex, true);
        $Correlation = $Correlation / $std_index;

        return $Correlation;
    }

    //// END ---- Fucntion tinh Beta cua co phieu
	
	/////////// BEGIN --- Tinh corelation
	protected function getCorelation($ticket, $dateBegin, $dateEnd) {
        $closeData = array();
        $fromMa = $dateBegin;
        $toMa = $dateEnd;
		$ReturnStep = 1;
		$Count = array();
		$ArrayReturn =array();
		$ArrayCorelation = array();
		
		foreach($ticket as $maChungKhoan) {
			//$StockObj = Company::model()->findByAttributes(array('ticket' => $maChungKhoan));
			$query = "companyID = " . $maChungKhoan . " and (timestamp BETWEEN '" . $fromMa . "' and '" . $toMa . "') ORDER BY timestamp ASC";
			$db = Stock::model()->findAll($query);
			array_push($Count,count($db));
		}
		$min = min ($Count);
		
        foreach($ticket as $maChungKhoan) {
			//$StockObj = Company::model()->findByAttributes(array('ticket' => $maChungKhoan));
			$query = "companyID = " . $maChungKhoan . " and (timestamp BETWEEN '" . $fromMa . "' and '" . $toMa . "') ORDER BY timestamp ASC";
			$db = Stock::model()->findAll($query);
			
			$count = count($db) - 1;
			$aaf = adjustPrice($db);
			for ($i = 0; $i <= $count; ++$i) {
				if ($db[$i]->close != '0' && $i % $ReturnStep == 0) {
				}
					$closeData[] = round($db[$i]->close * $aaf[$i], 3);
			}
			$dateStamp = array();
			for ($i = 0; $i <= $count; ++$i) {
				if ($db[$i]->timestamp != '0' && $i % $ReturnStep == 0)
					array_push($dateStamp, $db[$i]->timestamp);
			}
			$closeData = $this->matrixRotation($closeData);
			$dateStamp = $this->matrixRotation($dateStamp);
			$ReturnValueStock = array();
			for ($i = 0; $i < count($closeData) - 1; $i++) {

				if ($closeData[$i + 1] != 0)
					$Log10Temp = log(floatval($closeData[$i]) / floatval($closeData[$i + 1]));
				else
					$Log10Temp = log(floatval($closeData[$i] - 1) / floatval($closeData[$i]));

				array_push($ReturnValueStock, $Log10Temp);
			}
			
			array_push($ArrayReturn,$ReturnValueStock);			
			unset($ReturnValueStock);
		}
		for($i=0;$i<count($ticket);$i++)
		{
			for($j=0;$j<count($ticket);$j++)
			{
				 array_push($ArrayCorelation,Stock::model()->Correlation($ArrayReturn[$i],$ArrayReturn[$j]));
			}
		}
        return $ArrayCorelation;
    }
	
	////////// END --- Tinh corelation
	
	
    ///// BEGIN ---- Tinh Standard Deviation
    protected function getStandardDeviation($ticket, $dateBegin, $dateEnd) {
        $closeData = array();
        $fromMa = $dateBegin;
        $toMa = $dateEnd;
        $maChungKhoan = $ticket;
        $ReturnStep = 1;
        //$StockObj = Company::model()->findByAttributes(array('ticket' => $maChungKhoan));
        $query = "companyID = " . $maChungKhoan . " and (timestamp BETWEEN '" . $fromMa . "' and '" . $toMa . "') ORDER BY timestamp ASC";
        $db = Stock::model()->findAll($query);

        $count = count($db) - 1;
        $aaf = adjustPrice($db);
        for ($i = 0; $i <= $count; ++$i) {
            if ($db[$i]->close != '0' && $i % $ReturnStep == 0) {
                $closeData[] = round($db[$i]->close * $aaf[$i], 3);
            }
        }
        $dateStamp = array();
        for ($i = 0; $i <= $count; ++$i) {
            if ($db[$i]->timestamp != '0' && $i % $ReturnStep == 0)
                array_push($dateStamp, $db[$i]->timestamp);
        }
        $closeData = $this->matrixRotation($closeData);
        $dateStamp = $this->matrixRotation($dateStamp);
        $ReturnValueStock = array();
        for ($i = 0; $i < count($closeData) - 1; $i++) {

            if ($closeData[$i + 1] != 0)
                $Log10Temp = log(floatval($closeData[$i]) / floatval($closeData[$i + 1]));
            else
                $Log10Temp = log(floatval($closeData[$i] - 1) / floatval($closeData[$i]));

            array_push($ReturnValueStock, $Log10Temp);
        }
		
        return Stock::model()->standard_deviation($ReturnValueStock, true);
    }
	
	protected function getStandardDeviationByArray($ticket) {       
		
        return Stock::model()->standard_deviation($ticket, true);
    }

    //// END ---- Tinh Standard Deviation
    /// BEGIN --- Check array PortfolioStatus
    protected function getPortfolioStatusUpdateArray($array, $date, $ticket) {
        foreach ($array as $a) {
            if ($a[0] == $date && $a[1] == $ticket)
                return $a[4];
        }
        return 0;
    }

    /// END ---  Check array PortfolioStatus
    /// BEGIN --- Check array PortfolioStatus
    protected function getPortfolioStatusArray($array, $date, $ticket, $column) {
        foreach ($array as $a) {
            if ($a[0] == $date && $a[1] == $ticket)
                return $a[$column];
        }
        return 0;
    }
	protected function getPortfolioReturn1($arrayReturn, $arrayTime, $begin, $end)
	{
		$from = 0;
		$to = 0;
		$result = 1;
		for($i = 0; $i < count($arrayTime); $i++)
		{
			if($arrayTime[$i]==$begin) $from=$i;
			if($arrayTime[$i]==$end) $to=$i;
		}
		for($i=$from; $i<$to; $i++)
		{
			$result = $result*$arrayReturn[$i];
		}
		return $result - 1;
	}
	protected function getYield($year,$numberDay)
	{
		return pow((1+(float)12/100),($numberDay/365))-1;;
		$Yarray = array();
		$homepage = file_get_contents("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fbond.hnx.vn%2Fdefault.aspx%3FtabIndex%3D1%26tabid%3D35%22%20and%0A%20%20%20%20%20%20xpath%3D'%2F%2Fhtml%2Fbody%2Fform%2Ftable%2Ftr%2Ftd%2Ftable%2Ftr%2Ftd%2Ftable%2Ftr%2Ftd%2Ftable%2Ftr%2Ftd%2Fdiv%2Fdiv%5B%40id%3D%22AjaxPublishInfo%22%5D%2Fdiv%5B%40id%3D%22dvTodayMarket%22%5D%2Ftable%2Ftr%2Ftd%2Ftable%2Ftr%2Ftd%2Ftable%2Ftr%2Ftd%2Fp'&diagnostics=true");
			$html = str_get_html($homepage);
			foreach ($html->find('p') as $p) {
					array_push($Yarray,$p->innertext);
			}
		$value = 0;
		//if($year==1) $value = $Yarray[1];
		if($year==1) $value = 13.05;
		if($year==2) $value = $Yarray[4];
		if($year==3) $value = $Yarray[7];
		if($year==5) $value = $Yarray[10];
		if($year==7) $value = $Yarray[13];
		if($year==10) $value = $Yarray[16];
		if($year==15) $value = $Yarray[19];
		
		$value1 = str_replace(",", ".", $value);
		$result = pow((1+(float)$value1/100),(54/365))-1;
		return $result;
		
	}
	
	protected function getContribution($date, $stock, $port)
	{
		$connection = Yii::app()->db; // ket noi database
		$query = "SELECT companyID, SUM(quantity_m) as sum_quantity_m FROM portfolio WHERE portfolionameID = $port AND date = '" . $date . "' AND companyID = $stock AND type = 0 GROUP BY companyID"; // chon tat ca giao dich thuoc 1 ngay
		$command = $connection->createCommand($query);
        $dataReader = $command->queryAll();
		if(count($dataReader)>=1) {
			foreach ($dataReader as $now_data) {
				return $now_data['sum_quantity_m'];
			}
		} else return 0;
	}
	
	protected function getWithdrawal($date, $stock, $port)
	{
		$connection = Yii::app()->db; // ket noi database
		$query = "SELECT companyID, SUM(quantity_m) as sum_quantity_m FROM portfolio WHERE portfolionameID = $port AND date = '" . $date . "' AND companyID = $stock AND type = 1 GROUP BY companyID"; // chon tat ca giao dich thuoc 1 ngay
		$command = $connection->createCommand($query);
        $dataReader = $command->queryAll();
		if(count($dataReader)>=1) {
			foreach ($dataReader as $now_data) {
				return $now_data['sum_quantity_m'];
			}
		} else return 0;
		
	}
	
	protected function getAfterChange($arrayDate, $date, $stock)
	{
		$date_next = new DateTime($date);
        $date_next->modify('+1 day');
        $now_next = $date_next->format("Y-m-d 00:00:00");
        $date = $now_next;
		
		
		foreach($arrayDate as $temp_data)
		{
			if($temp_data[0]==$date&&$temp_data[1]==$stock)
			{
				return $temp_data[4];
			}
		}
		
		return 0;
	}
	
	
	protected function getComponentPortfolio($port, $stock, $quantity, $dateBegin, $dateEnd)
	{
		if($dateBegin<$dateEnd) {			
			$result = $quantity;
			$connection = Yii::app()->db;
			$query = "SELECT * FROM portfolio WHERE portfolionameID = $port AND (date BETWEEN '" . $dateBegin . "' and '" . $dateEnd . "') ORDER BY date ASC"; /// Chon tat ca nhung ngay thang trong khoang thoi gian cua accountID
			$command = $connection->createCommand($query);
			$dataReader = $command->queryAll();
			
			foreach ($dataReader as $row) {
					if($row['type']==0&&$row['date']!=$dateBegin) $result = $result + $row['quantity_m'];
					if($row['type']==1&&$row['date']!=$dateBegin) $result = $result - $row['quantity_m'];
			}
			return $result;
		} else if ($dateBegin > $dateEnd) {
			$result = $quantity;
			$connection = Yii::app()->db;
			$query = "SELECT * FROM portfolio WHERE portfolionameID = $port AND (date BETWEEN '" . $dateEnd . "' and '" . $dateBegin . "') ORDER BY date ASC"; /// Chon tat ca nhung ngay thang trong khoang thoi gian cua accountID
			$command = $connection->createCommand($query);
			$dataReader = $command->queryAll();
			foreach ($dataReader as $row) {
					if($row['type']==0&&$row['date']!=$dateEnd) $result = $result - $row['quantity_m'];
					if($row['type']==1&&$row['date']!=$dateEnd) $result = $result + $row['quantity_m'];				
			}
			return $result;
		} else return $quantity;
	}
	
    /// END ---  Check array PortfolioStatus
	
	
	
    public function actionPortfolioReturn() {
        $dataProvider = new CActiveDataProvider('Portfolio');
        $text = "";
		$PortfolioIndex = array();
        if (isset($_GET['from']) && isset($_GET['to'])) {

            // BEGIN - --- -- KHoi tao gia tri 
            $connection = Yii::app()->db; // ket noi database
            $fromDate = $_GET['from']; // Lay ngay bat dau
            $toDate = $_GET['to']; // lay ngay ket thuc
            $account = $_GET['port']; // account
            $pieces = explode("/", $fromDate); /// xu ly thong tin ngay bat dau
            $fromDate = $pieces[2] . "-" . $pieces[1] . "-" . $pieces[0] . " 00:00:00";
            $pieces = explode("/", $toDate); // xu ly thong tin ngay ket thuc
            $toDate = $pieces[2] . "-" . $pieces[1] . "-" . $pieces[0] . " 00:00:00";
            $DateArray = array(); /// luu thong tin cac ngay co giao dich
            $DateArray_one = array(); /// luu thong tin cac ngay co giao dich tinh tu ngay dau tien
            $DateFullArray = array();
            $PreDate = ""; /// Ngay truoc do;
            $PreValue = 0;
            $NowDate = ""; // Ngay hien tai
            $PortfolioStatus = array(); /// Theo cau truc sau (date, MaCoPhieu, QuantityAfter, ClosePrice, QuantityBefore, Contribution)
            $PortfolioStatusUpdate = array();
            $PortfolioReturnTable = array(); // Bang Portfolio Table
            $StockTicketArray = array(); /// Ma tran luu cac ticket
            $Setting_Brokerage_Fee = 0.002; //// Setting Brokerage Fee - Jensen Alpha (sample)
            $Market_Value_Proportion_Under = 0; /// Jensen Alpha (sample)
            $PortfolioBeforeArray = array();
            $PortfolioValue = array();
            $PortfolioReturnResult = array();
            $VNIndex = array();
			$portforlioReturn = 1; // Portfolioreturn
            $countDate = 0;
			$PortfolioReturnResultAddOne = array();
			
			

            // END ---- Khoi tao gia tri
            /// BEGIN --- Chon nhung ngay thang co du lieu
            $query = "SELECT DISTINCT date FROM portfolio WHERE portfolionameID = $account AND (date BETWEEN '" . $fromDate . "' and '" . $toDate . "') ORDER BY date ASC"; /// Chon tat ca nhung ngay thang trong khoang thoi gian cua accountID
            $command = $connection->createCommand($query);
            $dataReader = $command->queryAll();
            foreach ($dataReader as $row) {
                $countDate++;
				array_push($DateArray, $row['date']); /// them ngay vao mang DateArray                    
            }
			if($countDate>2)
			{
            //// END --- Chon nhung ngay thang co du lieu
            /// BEGIN --- Chon nhung ngay thang co du lieu
            $query = "SELECT DISTINCT date FROM portfolio WHERE portfolionameID = $account AND (date <= '" . $toDate . "') ORDER BY date ASC"; /// Chon tat ca nhung ngay thang trong khoang thoi gian cua accountID
            $command = $connection->createCommand($query);
            $dataReader = $command->queryAll();
            foreach ($dataReader as $row) {
                array_push($DateArray_one, $row['date']); /// them ngay vao mang DateArray                    
            }
            //// END --- Chon nhung ngay thang co du lieu

            /*
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              /////////////////////////////                     	PORTFOLIO RETURN                      //////////////
              //////////////////////////////////////////////////////////////////////////////////////////////////////
             */
            /// BEGIN --- Xu ly Portfolio Status
			//$text .= "<table><tr><td>Time</td><td>Ticket</td><td>Quantity after changes</td><td>Close Price</td><td>Quantity before changes</td><td>Contribution</td></tr>";
            foreach ($DateArray_one as $row) {
                $query = "SELECT companyID, SUM(quantity_m) as sum_quantity_m FROM portfolio WHERE portfolionameID = $account AND date <= '" . $row . "' GROUP BY companyID"; // chon tat ca giao dich thuoc 1 ngay
                $command = $connection->createCommand($query);
                $dataReader = $command->queryAll();
                foreach ($dataReader as $now_data) {
                    if ($PreDate != "" && $PreDate != null) { // kiem tra xem ngay bat dau co rong hay k
                        $query_child = "SELECT companyID, SUM(quantity_m) as sum_quantity_m FROM portfolio WHERE portfolionameID = $account AND (date <= '" . $PreDate . "') AND companyID = " . $now_data['companyID'] . " GROUP BY companyID"; // chon tat ca giao dich thuoc 1 ngay
                        $command_child = $connection->createCommand($query_child);
                        $dataReader_child = $command_child->queryAll();
                        foreach ($dataReader_child as $now_data_child) {
                            $PreValue = $now_data_child['sum_quantity_m'];
                        }
                        for ($i = 0; $i < count($PortfolioStatus); $i++) { /// kiem tra xem ma co phieu nay da duoc duyet truoc do hay chua, neu chua thi set  PreValue = 0
                            if ($PortfolioStatus[$i][1] == $now_data['companyID']) {
                                $i = count($PortfolioStatus);
                            }
                            if ($i == (count($PortfolioStatus) - 1))
                                $PreValue = 0;
                        }
                    }
                    $portfolioStatusTemp = array();
                    ///Theo cau truc sau (0:date, 1:MaCoPhieu, 2:QuantityAfter, 3:ClosePrice, 4:QuantityBefore, 5:Contribution, 6: withdrawl)
                    array_push($portfolioStatusTemp, $row); // Thoi gian
                    array_push($portfolioStatusTemp, $now_data['companyID']);  /// ma co phieu
                    array_push($portfolioStatusTemp, $now_data['sum_quantity_m']); /// So luong co phieu tinh den thoi diem hien tai								
                    array_push($portfolioStatusTemp, $this->getClosePrice($now_data['companyID'], $row)); /// Gia dong cua tai thoi diem ngay hom do
                    array_push($portfolioStatusTemp, $PreValue); /// So luong co phieu cua ngay hom truoc
                    array_push($portfolioStatusTemp, $now_data['sum_quantity_m'] - $PreValue);   // /contribution cua ngay hom do.
                    array_push($PortfolioStatus, $portfolioStatusTemp); /// luu vao ProtfolioStatus
                    $temp = $now_data['sum_quantity_m'] - $PreValue;
					$StockObj_temp_temp = Company::model()->findByAttributes(array('id' => $now_data['companyID']));
                    //$text .= "<tr><td>$row</td><td>" . $StockObj_temp_temp->ticket . "</td><td>" . $now_data['sum_quantity_m'] . "</td><td>" . $this->getClosePrice($now_data['companyID'], $row) . "</td><td>$PreValue</td><td>$temp</td></tr>";
                }
				
                $PreDate = $row;
            }
			//$text .= "</table>";
           // $text .= "<br><br>";
            /// BEGIN --- lay mang ticket
            foreach ($PortfolioStatus as $row_now) {
                if ($row_now[0] == $DateArray[count($DateArray) - 1]) {
                    array_push($StockTicketArray, $row_now[1]);
                    //array_push($PortfolioStatusUpdate, $row_now);
                }
            }
            /// END --- lay mang ticket
            /// BEGIN --- cap nhat status update
            $begin_date = new DateTime($fromDate);
            $begin_date->modify('-1 day');
            $begin_date_t = $begin_date->format("Y-m-d 00:00:00");
            $now = $PortfolioStatus[count($PortfolioStatus) - 1][0];
			$text .= "<table><tr><td>Time</td><td>Ticket</td><td>Quantity after changes</td><td>Close Price</td><td>Quantity before changes</td><td>Contribution</td><td>Withdrawal</td></tr>";
            while ($now != $begin_date_t) {
                array_push($DateFullArray, $now);
                $date_next = new DateTime($now);
                $date_next->modify('+1 day');
                $now_next = $date_next->format("Y-m-d 00:00:00");
                foreach ($StockTicketArray as $row_now) {
                    $portfolioStatusTemp = array();
                    array_push($portfolioStatusTemp, $now); // Thoi gian
                    array_push($portfolioStatusTemp, $row_now);  /// ma co phieu
                    if ($now == $PortfolioStatus[count($PortfolioStatus) - 1][0]) {
                        //array_push($portfolioStatusTemp, $this->getPortfolioStatusArray($PortfolioStatus, $now, $row_now, 2));
						/*if (isset($_GET['port']))
							$tickerCount = Portfolio::model()->findAll(array('select' => 'companyID', 'distinct' => true, 'condition' => "portfolionameID = " . $_GET['port']));
						else
							$tickerCount = "0";
						foreach ($tickerCount as $abc) {
								$ticker_Obj = Company::model()->findByAttributes(array('id' => $abc->companyID));
								if($row_now == $ticker_Obj->id) array_push($portfolioStatusTemp, $_GET[$ticker_Obj->ticket]);								
						}*/
						//function getComponentPortfolio($port, $stock, $quantity, $dateBegin, $dateEnd)
						$component_port = Componentportfolio::model()->findByAttributes(array('companyID' => $row_now, 'portfolionameID' => $_GET['port']));
						$temp_component = $this->getComponentPortfolio($_GET['port'],$row_now,$component_port->quantity,$component_port->date,$toDate);
						array_push($portfolioStatusTemp, $temp_component);
					}
                    else
                        array_push($portfolioStatusTemp, $this->getAfterChange($PortfolioStatusUpdate, $now, $row_now));
                    /// So luong co phieu tinh den thoi diem hien tai								
                    array_push($portfolioStatusTemp, $this->getClosePrice($row_now, $now)); /// Gia dong cua tai thoi diem ngay hom do
                    array_push($portfolioStatusTemp, 0);

					array_push($portfolioStatusTemp, $this->getContribution($now, $row_now, $account));   // /contribution cua ngay hom do.
					array_push($portfolioStatusTemp, $this->getWithdrawal($now, $row_now, $account));   // /contribution cua ngay hom do.
					$portfolioStatusTemp[4] = $portfolioStatusTemp[2] + $portfolioStatusTemp[6] - $portfolioStatusTemp[5];
					array_push($PortfolioStatusUpdate, $portfolioStatusTemp); /// luu vao ProtfolioStatus
                    //$text .= "(" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][0] . "," . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][1] . "," . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][2] . "," . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][3] . "," . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][4] . "," . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][5] . ")<br>";
					$StockObj_temp_temp = Company::model()->findByAttributes(array('id' => $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][1]));
					$text .= "<tr><td>" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][0] . "</td><td>" . $StockObj_temp_temp->ticket . "</td><td>" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][2] . "</td><td>" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][3] . "</td><td>" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][4] . "</td><td>" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][5] . "</td><td>" . $PortfolioStatusUpdate[count($PortfolioStatusUpdate) - 1][6] . "</td></tr>";

					}
                $date_previous = new DateTime($now);
                $date_previous->modify('-1 day');
                $now = $date_previous->format("Y-m-d 00:00:00");
            }
			$text .= "</table>";
            /// END --- cap nhat status update
            //$text .= $PortfolioStatus[count($PortfolioStatus)-1][0]-1;
            /// END --- Xu ly Portfolio Status		



            $text .="<br><br><br>";
            /// BEGIN --- Tao table portfolio return
			$text .= "<table><tr><td>Date</td><td>Portfolio value before contributions</td><td>Contributions</td><td>Withdrawls</td><td>Dividends</td><td>Portfolio value after all changes</td></tr>";			
            foreach ($DateFullArray as $row) {
                $query = "SELECT * FROM portfolio WHERE portfolionameID = $account AND date = '" . $row . "'"; // chon tat ca giao dich thuoc 1 ngay
                $command = $connection->createCommand($query);
                $dataReader = $command->queryAll();
				
				$query = "SELECT * FROM dividend WHERE portfolionameID = $account AND date = '" . $row . "'"; // chon tat ca giao dich thuoc 1 ngay
                $command_di = $connection->createCommand($query);
                $dataReader_di = $command_di->queryAll();
				$money = 0;
				foreach($dataReader_di as $now_data_di)
				{
					$money = $money + $now_data_di['money'];
				}
                $Contributions = 0;
				$Withdrawls = 0;
                $PortfolioBefore = 0;
				$PortfolioAfter = 0;
                foreach ($dataReader as $now_data) {
                    if($now_data['type']==0) $Contributions = $Contributions + $now_data['quantity_m'] * $now_data['price_m'];
					if($now_data['type']==1) $Withdrawls = $Withdrawls + $now_data['quantity_m'] * $now_data['price_m'];
                }
                //$Contributions = $Contributions * (1 - $Setting_Brokerage_Fee) * 1000;
				//$Withdrawls = $Withdrawls * (1 - $Setting_Brokerage_Fee) * 1000;
				$Contributions = $Contributions * 1000;
				$Withdrawls = $Withdrawls * 1000;
                for ($i = 0; $i < count($PortfolioStatusUpdate); $i++) {
                    /// BEGIN --- luu cac ticket
                    /*
                      Luu tat ca cac ticket ma nguoi dung da tung mua hoac ban
                      Tinh $Market_Value_Proportion_Under = sum(Quantity after changes * Close price) cua ngay cuoi cung
                     */
                    if ($row == $DateArray[count($DateArray) - 1] && $PortfolioStatusUpdate[$i][0] == $DateArray[count($DateArray) - 1]) {
                        //array_push($StockTicketArray, $PortfolioStatusUpdate[$i][1]);
                        $Market_Value_Proportion_Under += $PortfolioStatusUpdate[$i][4] * $PortfolioStatusUpdate[$i][3];
                    }
                    /// END --- Luu cac ticket

                    if ($PortfolioStatusUpdate[$i][0] == $row) {
                        $PortfolioBefore = $PortfolioBefore + $PortfolioStatusUpdate[$i][3] * $PortfolioStatusUpdate[$i][4];
						$PortfolioAfter = $PortfolioAfter + $PortfolioStatusUpdate[$i][3] * $PortfolioStatusUpdate[$i][2];
                        //$text .= "// $row ".$PortfolioStatusUpdate[$i][3]."*".$PortfolioStatusUpdate[$i][4]." <br><br>";
                    }
					
                }
                $PortfolioBefore = $PortfolioBefore * 1000;
				$PortfolioAfter = $PortfolioAfter * 1000;
                //if ($row == $DateArray[count($DateArray) - 1])
                    //$PortfolioBefore = $PortfolioBefore / 2;
                array_push($PortfolioBeforeArray, $PortfolioBefore);
                $PortfolioValue_tem = $PortfolioBefore + $Contributions - $Withdrawls + $money;
                //array_push($PortfolioValue, $PortfolioValue_tem);
				array_push($PortfolioValue, $PortfolioAfter);
                //$text .= "($row, $PortfolioBefore, $Contributions, $Withdrawls, $money, $PortfolioValue_tem)<br>";
				$text .= "<tr><td>$row</td><td>$PortfolioBefore</td><td>$Contributions</td><td>$Withdrawls</td><td>$money</td><td>$PortfolioAfter</td></tr>";
            }
			$text .= "</table>";
			$text .= "<br><br>";
            $temp_return = 1;
			$text .= "<table><tr><td>date end</td><td>portfolio return + 1</td></tr>";
            for ($i = 0; $i < count($PortfolioValue) - 1; $i++) {
                $temp = $PortfolioBeforeArray[$i] / $PortfolioValue[$i + 1];
                $temp_return = $temp_return * $temp;
                $text .= "<tr><td>".$DateFullArray[$i]."</td><td>".$temp."</td></tr>";
                array_push($PortfolioReturnResult, $temp);
				array_push($PortfolioReturnResultAddOne, $temp-1);
            }
			$text .= "</table>";
            $temp_return = $temp_return-1;
            $text .= "<br><br><b>Portfolio Return: </b>".$temp_return . "<br>";
			$portforlioReturn = $temp_return;
			$portforlioReturnYear = pow((1+$portforlioReturn),365/count($PortfolioReturnResult))-1;
			$text .= "<br><b>Annualised return: </b>".$portforlioReturnYear . "";
            /// END --- Tao table portfolio return

            /*
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              /////////////////////////////                     	JENSEN ALPHA                         //////////////
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              note yql for yield http://developer.yahoo.com/yql/console/#h=select%20*%20from%20html%20where%20url%3D%22http%3A//bond.hnx.vn/default.aspx%3FtabIndex%3D1%26tabid%3D35%22%20and%0A%20%20%20%20%20%20xpath%3D%27//html/body/form/table/tr/td/table/tr/td/table/tr/td/table/tr/td/div/div%5B@id%3D%22AjaxPublishInfo%22%5D/div%5B@id%3D%22dvTodayMarket%22%5D/table/tr/td/table/tr%27
             */
			 $text .= "<br><br>//////////////////////////////////////////////////////////////////////////////////////////////////////<br>
              /////////////////////////////                     	JENSEN ALPHA                         //////////////<br>
              //////////////////////////////////////////////////////////////////////////////////////////////////////<br><br>";
			$Yield = $this->getYield(1,count($PortfolioReturnResult));
			$Market_Value_Array = array();
			$Beta_Portfolio = 0;
			$JensenAnpha = 0;
			$Beta_Stock = array();
            //$text .= "<br><br>Tinh Beta: <br>";
            ///// BEGIN - Tinh beta - su dung ham getBetaStock
            foreach ($StockTicketArray as $StockTicket) {
				$temp_stock = $this->getBetaStock($StockTicket, '2009-10-31 00:00:00', '2011-10-31 00:00:00', 1, 1);
                $text .= $temp_stock . "<br>";
				array_push($Beta_Stock,$temp_stock);
				//$Beta_Portfolio = $Beta_Portfolio * $temp_stock;
            }
			
			
            //$text .= "<br>" . $Market_Value_Proportion_Under;
			//$Market_Value_Proportion_Under = $Market_Value_Proportion_Under/2;
			$text .= $Market_Value_Proportion_Under . "<br>";
			$vnindex_id = Company::model()->find("ticket = 'VNINDEX'")->id;
			
			$returnOfBenchmark = $this->getClosePrice($vnindex_id,$DateArray[count($DateArray)-1])/$this->getClosePrice($vnindex_id,$DateArray[0]) - 1;
			//$text .= "<br>".$returnOfBenchmark;
			for ($i = 0; $i < count($PortfolioStatusUpdate); $i++) {
				if($PortfolioStatusUpdate[$i][0]==$DateArray[count($DateArray)-1])
				{
					$temp = $PortfolioStatusUpdate[$i][4]*$PortfolioStatusUpdate[$i][3];
					$text .= "<br>".$temp;
					$temp = $temp/$Market_Value_Proportion_Under;
					array_push($Market_Value_Array,$temp);
					//$Beta_Portfolio = $temp * $Beta_Portfolio;
					$text .= "<br>".$temp;
				}
			}
			for($i = 0; $i<count($Market_Value_Array); $i++)
			{
				$Beta_Portfolio = $Beta_Portfolio + $Beta_Stock[$i]*$Market_Value_Array[$i];
			}
			//$text .= "<br>".$Beta_Portfolio;
			$JensenAnpha = $portforlioReturn - ($Yield+$Beta_Portfolio*($returnOfBenchmark-$Yield));
			$text .= "<br><br><br>DATA------------------------------------------------------";
			$text .= "<br>Portfolio Return: ".$portforlioReturn;
			$text .= "<br>Yield(1year): ".$Yield;
			$text .= "<br>Beta Portfolio: ".$Beta_Portfolio;
			$text .= "<br>Return of benchmark: ".$returnOfBenchmark;
			$text .= "<br>DATA------------------------------------------------------<br><br><br>";
			
			$text .= "Jensen: ".$JensenAnpha;
			

            ///// END - Tinh beta - su dung ham getBetaStock		
            /*
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              /////////////////////////////                     	SHARPE RATIO                         //////////////
              //////////////////////////////////////////////////////////////////////////////////////////////////////
             */
			$text .= "<br><br>//////////////////////////////////////////////////////////////////////////////////////////////////////<br>
              /////////////////////////////                     	SHARPE RATIO                         //////////////<br>
              //////////////////////////////////////////////////////////////////////////////////////////////////////<br><br>";
            $Corelation = array();
			$Standev = array();
			$Standev_Portfolio = 0;
			$StandevPow = 0;
			$Standard_Deviation = 0;
			//$Market_Value_Array
			
			$text .= "<br>DATA------------------------------------------------------<br><br>";
			//$Standard_Deviation = pow($Standev_Portfolio+$StandevPow,0.5);
			$Standard_Deviation = $this->getStandardDeviationByArray($PortfolioReturnResultAddOne);
			$text .= "<br><br><br>Standard deviation of the Portfolio : ".$Standard_Deviation;
			$text .= "<br>Yield(1year): ".$Yield;
			$text .= "<br>Portfolio Return: ".$portforlioReturn;
			$Sharpe_Ratio = ($portforlioReturn-$Yield)/$Standard_Deviation;
			$text .= "<br><br><br>Sharpe Ratio: ".$Sharpe_Ratio;
		
            ///// END - Tinh beta - su dung ham getBetaStock
            /*
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              /////////////////////////////                     	TREYNOR RATIO                        //////////////
              //////////////////////////////////////////////////////////////////////////////////////////////////////
             */
			 $text .= "<br><br>//////////////////////////////////////////////////////////////////////////////////////////////////////<br>
              /////////////////////////////                     	TREYNOR RATIO                         //////////////<br>
              //////////////////////////////////////////////////////////////////////////////////////////////////////<br><br>";
			$TreynorRatio = 0;
			
			$text .= "<br><br><br>DATA------------------------------------------------------";
			$text .= "<br>Portfolio Return: ".$portforlioReturn;
			$text .= "<br>Yield(1year): ".$Yield;
			$text .= "<br>Beta Portfolio: ".$Beta_Portfolio;
			$text .= "<br>DATA------------------------------------------------------<br><br><br>";
			
			$TreynorRatio = ($portforlioReturn-$Yield)/$Beta_Portfolio;
			
			$text .= "<br>Treynor Ratio: ". $TreynorRatio;
			


 /*
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              /////////////////////////////                     	INFORMATION RATIO                    //////////////
              //////////////////////////////////////////////////////////////////////////////////////////////////////
             */
			  $text .= "<br><br>//////////////////////////////////////////////////////////////////////////////////////////////////////<br>
              /////////////////////////////                     	INFORMATION RATIO                          //////////////<br>
              //////////////////////////////////////////////////////////////////////////////////////////////////////<br><br>";
///getPortfolioReturn1
//$DateFullArray
//$PortfolioReturnResult
//matrixRotation
			$DateFullArray3 = array();
			$DateFullArray3 = $this->matrixRotation($DateFullArray);
			
			//array_push($DateFullArray3,$fromDate);
			//$DateFullArray3 = $this->matrixRotation($DateFullArray3);

			$DateFullArray2 = array();
			$DateFullArray2 = $this->matrixRotation($DateFullArray);
			
			$PortfolioReturnResult2 = array();
			$PortfolioReturnResult2 = $this->matrixRotation($PortfolioReturnResult);
			
            $text .= "Inforatio:<br />";
            $criteria = new CDbCriteria;
            $criteria->distinct = true;
            $criteria->select = array("date");
            $criteria->addBetweenCondition("date", $fromDate, $toDate);

            $portfs = Portfolio::model()->findAll($criteria);

            $temp = array();
            $actreturn = array();
            $vnindexid = Company::model()->find("ticket = 'VNINDEX'")->id;
            $VNIndex = Stock::model()->findAll("companyID = $vnindexid and timestamp BETWEEN '$fromDate' and '$toDate' ORDER BY timestamp ASC");
			
			//print_r($DateFullArray3);
			
			$text .= "<br>DATA------------------------------------------------------<br><br><br>";
			$text .= "<table><tr><td>From</td><td>To</td><td>Portfolio Return</td><td>VN-Index</td><td>Active return</td></tr>";
            for ($i = 0; $i < count($DateFullArray3) - 1; ++$i) {
                $temp[$i]["from"] = $DateFullArray3[$i];
                $temp[$i]["to"] = $DateFullArray3[$i + 1];
                $temp[$i]["vnindex"] = ($this->getClosePrice($vnindexid, $temp[$i]["to"]) / $this->getClosePrice($vnindexid, $temp[$i]["from"])) - 1;
                $temp[$i]["preturn"] = $this->getPortfolioReturn1($PortfolioReturnResult2, $DateFullArray2, $temp[$i]["from"], $temp[$i]["to"]);
				$temp[$i]["actreturn"] = $temp[$i]["preturn"] - $temp[$i]["vnindex"];
				
                $actreturn[$i] = $temp[$i]["actreturn"];
				$text .= "<tr><td>".$temp[$i]["from"]."</td><td>".$temp[$i]["to"]."</td><td>".$temp[$i]["preturn"]."</td><td>".$temp[$i]["vnindex"]."</td><td>".$temp[$i]["actreturn"]."</td></tr>";
            }                
			$text .="</table>";
            $standev_information_ratio = Stock::model()->standard_deviation($actreturn, true);
			$text .= "<br>Return of the portfolio: ".$portforlioReturn;	
			$text .= "<br>Return of the benchmark: ".$returnOfBenchmark;	
			$text .= "<br>Standard deviation of active return: ".$standev_information_ratio;	

			$text .= "<br>DATA------------------------------------------------------<br><br><br>";
            $inforatio = ($portforlioReturn - $returnOfBenchmark) / $standev_information_ratio;
			$text .= "<br><br>Information Ratio: ".$inforatio;
			
			
            /*
              //////////////////////////////////////////////////////////////////////////////////////////////////////
              /////////////////////////////                     PORTFOLIO INDEX                       //////////////
              //////////////////////////////////////////////////////////////////////////////////////////////////////
             */
			 	  $text .= "<br><br>//////////////////////////////////////////////////////////////////////////////////////////////////////<br>
              /////////////////////////////                     	PORTFOLIO INDEX                           //////////////<br>
              //////////////////////////////////////////////////////////////////////////////////////////////////////<br><br>";

            $text .= "<br />Portfolio Index: <br />";
            $isChanged = false;
            
            $currCount = 0;
            //$VNIndex = Stock::model()->findAll("companyID = $vnindexid and timestamp BETWEEN '".$fromDate."' and '$toDate' ORDER BY timestamp ASC");
            $count = count($DateFullArray) - 1;
	$currIndex = count($PortfolioStatusUpdate) - 1;
			$text .="<table><tr><td>Port. Value (before changes)</td><td>Adjusted Value</td><td>Date</td><td>Portfolio Index</td><td>Maket Index</td></tr>";
                for ($i = $count; $i >= 0; --$i) {
                    $day = $DateFullArray[$i];
                    $PortfolioIndex[$i]['date'] = $day;
                    $PortfolioIndex[$i]['currVal'] = 0;
                    $PortfolioIndex[$i]['adjVal'] = 0;
                    $PortfolioIndex[$i]['pIndex'] = 0;
                    
                    
                    $currCount = $this->countPortfolioStatus($PortfolioStatusUpdate, $day, $currIndex);
                    
                    if ($i != $count) {
                        
                        //$todayIndex = Stock::model()->find("timestamp = '$DateFullArray[$i]'");

                        /*if ($todayIndex == null) {
                            $PortfolioIndex[$i]['currVal'] = $PortfolioIndex[$i + 1]['currVal'];
                            $PortfolioIndex[$i]['adjVal'] = $PortfolioIndex[$i + 1]['adjVal'];
                            $PortfolioIndex[$i]['pIndex'] = $PortfolioIndex[$i + 1]['pIndex'];
                            $PortfolioIndex[$i]['marketIndex'] = $PortfolioIndex[$i + 1]['marketIndex'];
                        } else */{
                            $PortfolioIndex[$i]['marketIndex'] = $this->getClosePrice($vnindexid, $DateFullArray[$i]) / $this->getClosePrice($vnindexid, $DateFullArray[$count]) * 100;
                            $BeforeChangeQuantity = 0;
                            $AfterChangeQuantity = 0;
                            for ($j = 0; $j < $currCount; ++$j) {
                                $BeforeChangeQuantity += $PortfolioStatusUpdate[$currIndex - $j][2];
                                $AfterChangeQuantity += $PortfolioStatusUpdate[$currIndex - $j][4];
                                $PortfolioIndex[$i]['currVal'] += $PortfolioStatusUpdate[$currIndex - $j][4] * $PortfolioStatusUpdate[$currIndex - $j][3];
                                //echo $PortfolioStatusUpdate[$currIndex - $j][2]."*". $PortfolioStatusUpdate[$currIndex - $j][4] . " = " .($PortfolioStatusUpdate[$currIndex - $j][2] * $PortfolioStatusUpdate[$currIndex - $j][3]) . " - " . $PortfolioIndex[$i]['currVal'] . " - " .$day . "<br />";
                                if($isChanged == true) {
                                    $prevRow = $this->searchTickerByDate($PortfolioStatusUpdate, $DateFullArray[$i + 1], $PortfolioStatusUpdate[$currIndex - $j][1]);
                                    $PortfolioIndex[$i]['adjVal'] += $PortfolioStatusUpdate[$currIndex - $j][4] * $PortfolioStatusUpdate[$prevRow][3];
                                }
                            }
                            if($isChanged == true) {
                                $PortfolioIndex[$i]['adjVal'] = $PortfolioIndex[$i]['adjVal'] * $PortfolioIndex[$i + 1]['adjVal'] / $PortfolioIndex[$i + 1]['currVal'];
                            } else {
                                $PortfolioIndex[$i]['adjVal'] = $PortfolioIndex[$i + 1]['adjVal'];
                            }
                            
                            if ($BeforeChangeQuantity != $AfterChangeQuantity)
                                $isChanged = true;
                            else
                                $isChanged = false;
                        }
                    } else {
                        $PortfolioIndex[$i]['marketIndex'] = 100;
                        $BeforeChangeQuantity = 0;
                        $AfterChangeQuantity = 0;
                        
                        for ($j = 0; $j < $currCount; ++$j) {
                            $BeforeChangeQuantity += $PortfolioStatusUpdate[$currIndex - $j][2];
                            $AfterChangeQuantity += $PortfolioStatusUpdate[$currIndex - $j][4];
                            $PortfolioIndex[$i]['currVal'] += $PortfolioStatusUpdate[$currIndex - $j][4] * $PortfolioStatusUpdate[$currIndex - $j][3];
                        }
                        $PortfolioIndex[$i]['adjVal'] = $PortfolioIndex[$i]['currVal'];

                        if($BeforeChangeQuantity != $AfterChangeQuantity)
                            $isChanged = true;
                        else
                            $isChanged = false;
                    }
                    $currIndex = $this->searchPortfolioStatus($PortfolioStatusUpdate, $day, $currIndex);
                    $PortfolioIndex[$i]['pIndex'] = $PortfolioIndex[$i]['currVal'] / $PortfolioIndex[$i]['adjVal'];
                    // $text .= $PortfolioIndex[$i]['date'] . " " . $VNIndex[$i]->close . " " . $PortfolioIndex[$i]['currVal'] . " " .$PortfolioIndex[$i]['adjVal']. "||| " .$PortfolioIndex[$i]['pIndex']. ", " . $PortfolioIndex[$i]['marketIndex'] . "<br />";
                    $PortfolioIndex[$i]['pIndex'] = $PortfolioIndex[$i]['pIndex'] * 100;
                    //$text .= $PortfolioIndex[$i]['date'] . ", " .$PortfolioIndex[$i]['pIndex']. ", " . $PortfolioIndex[$i]['marketIndex'] . "<br />";
                    $text .= "<tr><td>".$PortfolioIndex[$i]['currVal']."</td><td>".$PortfolioIndex[$i]['adjVal']."</td><td>" . $PortfolioIndex[$i]['date'] . "</td><td>" . $PortfolioIndex[$i]['pIndex'] . "</td><td>" . $PortfolioIndex[$i]['marketIndex'] . "</td></tr>";
                }
                $text .= "</table>";
                $PortfolioIndex[0]['pIndex'] = 100;
            } else
                $text = "DÆ°̀ƒ liĂª̀£u bà£n thĂªm và€o quà? ì?t!";
        } //////////////////// ket thuc phan xu ly

        $this->render('portfolioReturn', array(
            'dataProvider' => $dataProvider, 'text' => $text, 'data_portfolio' => $PortfolioIndex,
        ));
    }
    
    public function searchPortfolioStatus($PortfolioStatus, $date, $startIndex = 0) {
        $i = ($startIndex <= count($PortfolioStatus) - 1) ? $startIndex : count($PortfolioStatus) - 1;
        for (; $i >= 0; --$i) {
            if ($PortfolioStatus[$i][0] != $date) {
                return $i;
            }
        }
        return -1;
    }
    
    public function countPortfolioStatus($PortfolioStatus, $date, $startIndex) {
        $count = 0;
        for ($i = $startIndex; $i >= 0; --$i) {
            if ($PortfolioStatus[$i][0] == $date)
                ++$count;
            else
                break;
        }
        return $count;
    }
    public function searchTickerByDate($PortfolioStatus, $date, $ticker) {
        for($i = 0; $i < count($PortfolioStatus); ++$i) {
            if($PortfolioStatus[$i][1] == $ticker && $PortfolioStatus[$i][0] == $date)
                return $i;
        }
        return -1;
    }
    
    //Calculate Information Ratio
    protected function getInformationRatio($dateBegin, $dateEnd, $portReturnArray, $returnofBenchmark) {
        $criteria = new CDbCriteria;
        $criteria->distinct = true;
        $criteria->select = array("date");
        $criteria->addBetweenCondition("date", $dateBegin, $dateEnd);

        $portfs = Portfolio::model()->findAll($criteria);

        $temp = array();
        $actreturn = array();
        $vnindexid = Company::model()->find("ticket = 'VNINDEX'")->id;
        $temp[0]["preturn"] = -3.04 / 100;
        $temp[1]["preturn"] = -0.88 / 100;
        $temp[2]["preturn"] = -0.43 / 100;
        $temp[3]["preturn"] = 0.35 / 100;
        $temp[4]["preturn"] = 2.61 / 100;

        $returnofBenchmark = -4.61/100 ;
        
        for ($i = 0; $i < count($portfs) - 1; ++$i) {
            $temp[$i]["from"] = $portfs[$i]->date;
            $temp[$i]["to"] = $portfs[$i + 1]->date;
            $temp[$i]["vnindex"] = ($this->getClosePrice($vnindexid, $temp[$i]["to"]) / $this->getClosePrice($vnindexid, $temp[$i]["from"])) - 1;
            $temp[$i]["actreturn"] = $temp[$i]["preturn"] - $temp[$i]["vnindex"];
            $actreturn[$i] = $temp[$i]["actreturn"];
        }

        $standev = Stock::model()->standard_deviation($actreturn, true);
        $inforatio = ($returnofPortfolio - $returnofBenchmark)/$standev;
        
        return $inforatio;
    }

    public function actionTesting() {
        $rop = -4.44/100;
        $rob = 0;
        $portfs = $this->getInformationRatio("2011-07-01", "2011-07-29",$rop, $rop );

        $this->render('testing', array(
            'portfs' => $portfs,
        ));
    }

}